import React from 'react';
import './index.css';
import { InputItem, List, Toast } from 'antd-mobile';
import mzsdk from '../../../../utils/mzsdk'
import MZListView from '../../../../components/MZListView';

/**
 * 问答组件
 */

export default class Discuss extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            is_anonymous: false,//是否匿名
            question: '',//问题
            is_show_my_discuss: false,//是否显示的是我提问的问题回答
            unread_count: 0,//未读个数

            allData: [],//该活动的所有问答
            myData: [],//我提问的所有问答

            showData: [],//当前展示的列表
            hasMore: true,
            refreshing: false,
            isLoading: false,
            limit: 50,
        }
    }

    componentWillUnmount() {
        mzsdk.mzee.off('updateAllReplyMsg')
        mzsdk.mzee.off('discuss_updateFrame')
        mzsdk.mzee.off('discuss-request-data');
    }

    componentDidMount() {
        var _this = this;

        setTimeout(() => {
            this.fixViewFrame();
        }, 1000);

        mzsdk.mzee.on("updateAllReplyMsg", function (e) {
            console.log('更新问答个数:',e.no_read_count)
            _this.setState({
                unread_count: e.no_read_count
            }, () => {
                _this.fixViewFrame();
            })
        })

        mzsdk.mzee.on("discuss_updateFrame", function () {
            _this.fixViewFrame()
        })

        mzsdk.mzee.on('discuss-request-data', function () {
            _this.getData(false)
        });
    }

    fixViewFrame = () => {
        let window_height = window.innerHeight

        var video = document.getElementById('main-top-video-super-background')
        var rollingView = document.getElementById('rolling-ad-background')
        var menuView = document.getElementById('tab-menu-background')
        var topTip = document.getElementById('discuss-top-tip')
        var askView = document.getElementById('discuss-ask-view')

        if (!video || !rollingView || !menuView || !topTip || !askView) {
            return;
        }
        let height = (window_height - video.clientHeight - rollingView.clientHeight - menuView.clientHeight - topTip.clientHeight - askView.clientHeight) + 'px'

        var discussListBackground = document.getElementById('discuss-content-background')
        if (discussListBackground) {
            discussListBackground.style.height = height
        }

        var discussList = document.getElementsByClassName('discuss-list-background')[0]
        if (discussList) {
            discussList.style.height = height
        }
    }

    selectAnonymous = () => {
        this.setState({
            is_anonymous: !this.state.is_anonymous
        })
    }

    onChangeText = (value) => {
        this.setState({ question: value });
    }

    submitQuestion = () => {
        var _this = this;
        var discussParam = {
            ticketId: this.props.ticketInfo.ticket_id,//活动ID
            content: this.state.question,//提问的问题，不能为空
            isAnonymous: this.state.is_anonymous ? '1' : '0'//是否匿名提问？ 0-否 1-是,必须字符串
        }
        mzsdk.discuss.submitDiscussQuestion(discussParam).then(function (res) {
            _this.setState({
                question: ''
            })
            if (_this.state.is_show_my_discuss == false) {
                _this.getData(false)
            }
        }, function (err) {
            Toast.info(err.msg, 1.5)
        })
    }

    clickAll = () => {
        this.setState({
            is_show_my_discuss: false,
            refreshing: false,
            isLoading: false,
            hasMore: true
        }, () => {
            this.getData(false)
        })
    }

    clickMy = () => {
        this.setState({
            is_show_my_discuss: true,
            refreshing: false,
            isLoading: false,
            hasMore: true,
            unread_count: 0
        }, () => {
            this.getData(false)
        })
    }

    getData = (isMore) => {
        var _this = this;
        var offset = '0';
        if (this.state.is_show_my_discuss) {
            this.state.limit = 200;//如果是我的问题有新的回答，默认显示200=条数据，不分页
        }
        if (isMore) {
            if (this.state.is_show_my_discuss) {
                offset = this.state.myData.length
            } else {
                offset = this.state.allData.length
            }
        }
        var discussParam = {
            ticketId: this.props.ticketInfo.ticket_id,//活动ID
            isNewReply: this.state.is_show_my_discuss ? '1' : '0',//是否查询有未读的回复， 0-不查询 1-查询
            offset: offset,//偏移,当前已经返回的数据总个数
            limit: _this.state.limit//请求返回的列表个数
        }
        mzsdk.discuss.getDiscussList(discussParam).then(function (res) {
            let tempArr = res.list ? res.list : [];
            if (!isMore) {
                if (_this.state.is_show_my_discuss) {
                    var new_myData = tempArr;
                    _this.setState({
                        allData: [],
                        unread_count: 0,
                        showData: new_myData,
                        myData: new_myData
                    }, () => {
                        _this.fixViewFrame()
                    })
                } else {
                    var new_allData = tempArr;
                    _this.setState({
                        myData: [],
                        unread_count: res.unread,
                        showData: new_allData,
                        allData: new_allData
                    }, () => {
                        _this.fixViewFrame()
                    })
                }
                _this.setState({
                    refreshing: false,
                    hasMore: tempArr.length >= _this.state.limit ? true : false
                })
            } else {
                if (tempArr.length < _this.state.limit) {
                    _this.setState({
                        isLoading: false,
                        hasMore: false
                    })
                } else {
                    _this.setState({
                        isLoading: false
                    })
                }
                if (_this.state.is_show_my_discuss) {
                    var new_myData = _this.state.myData.concat(tempArr)
                    _this.setState({
                        myData: new_myData,
                        showData: new_myData,
                    })
                } else {
                    var new_allData = _this.state.allData.concat(tempArr)
                    _this.setState({
                        allData: new_allData,
                        showData: new_allData,
                    })
                }
            }
        }, function (err) {
            Toast.info(err.msg, 1.5)
            _this.setState({
                isLoading: false,
                refreshing: false,
            })
        })
    }

    // 下拉刷新
    onRefresh = () => {
        this.setState({
            refreshing: true,
            hasMore: true
        }, () => {

            this.getData(false)
        })
    }

    // 滑动到底部时加载更多
    onEndReached = (event) => {
        if (this.state.isLoading || !this.state.hasMore) {
            return
        }
        this.setState({
            isLoading: true,
        }, () => {

            this.getData(true)
        })
    }

    render() {
        let { is_anonymous, question, is_show_my_discuss, unread_count, myData, allData, limit } = this.state;
        const row = (rowData, sectionID, rowID) => {
            // 这里rowData,就是上面方法cloneWithRows的数组遍历的单条数据了，直接用就行
            return (
                <div key={rowID} className="discuss-item-background">
                    <div className="discuss-item-user">
                        <img className="discuss-item-user-avatar" src={rowData.avatar}></img>
                        <div>
                            <div className="discuss-item-user-name">{rowData.nickname}</div>
                            <div className="discuss-item-user-time">{rowData.datetime}</div>
                        </div>
                    </div>
                    <div className="discuss-item-content-background">
                        <div className="discuss-item-content" style={{ marginBottom: rowData.replys && rowData.replys.length > 0 ? '0.2rem' : '0rem' }}>{rowData.content}</div>
                        {
                            rowData.replys && rowData.replys.map((item, index) => {
                                return (
                                    <div className="discuss-item-replay" key={index}>
                                        <div className="discuss-item-replay-user-name">{item.nickname}：</div>
                                        <div className="discuss-item-replay-content">{item.content}</div>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div >
            )
        }
        return (
            <div className="discuss-background" >
                {
                    this.props.ticketInfo ? <div>
                        <div className="discuss-top-tip" id="discuss-top-tip">
                            {
                                is_show_my_discuss ? <div className="top-tip-item" onClick={this.clickAll}>
                                    查看全部回答
                                </div> : <div>
                                    {
                                        unread_count > 0 && <div className="top-tip-item" onClick={this.clickMy}>
                                            您有新的回复({unread_count})
                                        </div>
                                    }
                                </div>
                            }
                        </div>
                        <div className="discuss-content-background" id="discuss-content-background">
                            {
                                (is_show_my_discuss && myData.length > 0) || (is_show_my_discuss == false && allData.length > 0) ?
                                    <MZListView
                                        className="discuss-list-background"
                                        data={this.state.showData}
                                        renderFooter={() => ((is_show_my_discuss == false && allData.length >= limit) && <div className="discuss-footer">{this.state.isLoading ? '加载中...' : '暂无更多数据'}</div>)}
                                        renderRow={row}
                                        initialListSize={limit}

                                        onPullToRefresh={is_show_my_discuss == false ? true : false}
                                        refreshing={this.state.refreshing}
                                        onRefresh={this.onRefresh}

                                        onEndReached={this.onEndReached}
                                    /> :
                                    <div className="discuss-empty-question">还没有人提问</div>
                            }
                        </div>
                    </div> :
                        <div className="discuss-empty-question">还没有人提问</div>

                }
                <div className="discuss-ask-view" id="discuss-ask-view">
                    <img className="mzAnonymousImage" src={is_anonymous == true ? require('../../../../assets/images/mz_anonymous_icon_checked.png') : require('../../../../assets/images/mz_anonymous_icon_check.png')} onClick={this.selectAnonymous}></img>
                    <div className="mzAnonymousText" onClick={this.selectAnonymous}>匿名</div>
                    <div className="mz-anonymous-input">
                        <List>
                            <InputItem name="question" type="text" placeholder="请输您的问题" value={question} defaultValue={question} onChange={this.onChangeText}></InputItem>
                        </List>
                    </div>
                    <div className="submit-button" onClick={this.submitQuestion}>提问</div>
                </div>
            </div>
        )
    }
}
